/*
*  路由拦截器, 用于判断拦截替换页面
* */
import store from '../store'
import 重置到首页 from './back'

const {getters, state} = store

// 判断为单站则直接跳过选择门店
const 选择油站 = async (to, from, next) => {
  if (to.name !== 'yjjy_xzyz') return false
  const shopList = await $g.shopListAsync()
  const params = shopList[0]
  if (shopList.length == 1) {
    if (params.butted) {
      next({...to, name: 'yjjy_xxdj', replace: true, params})
    } else {
      next({...to, name: 'yjjy', replace: true, params})
    }
    return true
  }
  return false
}

// 判断门店是否开启线下对接接口, 有则跳转到线下对接支付页面
const 一键加油 = (to, from, next) => {
  // 有线下接口则打开线下加油页面
  if (!(to.params.butted && to.name == 'yjjy')) return
  next({...to, name: 'yjjy_xxdj', replace: true})
  return true
}

// 已绑定,显示已绑定详情页
const 手机绑定 = (to, from, next) => {
  if (to.name == 'phoneBind' && !isEmpty(getters.userInfo.mobile) && !to.query.replace) {
    next({...to, name: 'phone_bind_always', replace: true})
    return true
  }
}

// 认证中，显示认证中页。 认证成功显示认证成功页
const 专车认证 = (to, from, next) => {
  if (to.name == 'specialCar_step1' && !to.query.replace) {
    switch (getters.userInfo.carState) {
      case 1:
        next({...to, name: 'specialCar_step4', replace: true})
        return true
      case 2:
        next({...to, name: 'specialCar_already', replace: true})
        return true
    }
  }
}

// 拦截器数组 函数返回true 则阻断
const arr = [选择油站, 一键加油, 手机绑定, 专车认证]
async function interceptor (to, from, next) {
  for (let i = 0; i < arr.length; i++) {
    if (await arr[i](to, from, next) === true) return
  }
  next()
}

export default interceptor